package cn.it.action;


import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;

import cn.it.pageModel.DataGrid;
import cn.it.pageModel.User;
import cn.it.service.UserService;
import cn.it.util.Json;

@Namespace("/")
@Action(value = "userAction")
public class UserAction extends BaseAction implements ModelDriven<User> {

	private static final Logger logger = Logger.getLogger(UserAction.class);

	private User user = new User();

	@Override
	public User getModel() {
		// TODO Auto-generated method stub
		return user;
	}

	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void reg() {
		Json j = new Json();
		try {
			user = userService.save(user);
			j.setSuccess(true);
			j.setMsg("注册成功");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("注册失败");
		}
		super.writeJson(j);
	}
	
	public void add() {
		Json j = new Json();
		try {
			user = userService.save(user);
			j.setSuccess(true);
			j.setMsg("添加成功");
			j.setObj(user);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("添加失败");
		}
		super.writeJson(j);
	}

	public void login() {
		Json j = new Json();
		User u = userService.login(user);
		if (u != null) {
			j.setSuccess(true);
			j.setMsg("登录成功");
		} else {
			j.setSuccess(false);
			j.setMsg("登录失败,用户名或密码错误");
		}
		super.writeJson(j);
	}

	public void datagrid(){
		super.writeJson(userService.datagrid(user));
	}
	
	public void remove(){
		userService.remove(user.getIds());
		Json j = new Json();
		j.setSuccess(true);
		j.setMsg("删除成功");
		super.writeJson(j);
	}
	
	public void edit(){
		userService.edit(user);
		Json j = new Json();
		j.setSuccess(true);
		j.setMsg("编辑成功");
		j.setObj(user);
		super.writeJson(j);
	}
}
